package servlets;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.dao.UserDAO;
import model.entity.User;
import servlets.util.ParamUtil;
import util.EncryptUtil;
import util.JSONUtil;
import exceptions.ParameterNotFoundException;

/**
 * Servlet implementation class SignupServlet
 */
@WebServlet("/SignupServlet")
public class SignupServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SignupServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<String> paramNames = Arrays.asList("user_name",
				"user_mail", "user_description", "user_password");
		Map<String, String> params = new HashMap<String, String>();
		try {
			params = ParamUtil.getValues(request, paramNames);
		} catch (ParameterNotFoundException e) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		UserDAO dao = new UserDAO(User.class);
		if(dao.existsMail(params.get("user_mail"))) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		User u = new User();
		u.setDescription(params.get("user_description"));
		u.setMail(params.get("user_mail"));
		u.setName(params.get("user_name"));
		u.setSalt(EncryptUtil.generateRandomString());
		u.setPassword(EncryptUtil.makePassword(params.get("user_password")));
		dao.create(u);
		response.setStatus(HttpServletResponse.SC_OK);		
		User uf = new User();
		uf.setName(u.getName());
		uf.setMail(u.getMail());
		response.getWriter().write(JSONUtil.toJSON(uf));
	}

}
